// pages/cart/index.js
// 添加收货地址
//  1.调用微信自带的获取收货地址的api
// 2.正常流程
      // 1.先调用获取用户对小程序的授权接口，有返回值
        // 2. 对权限scope进场判断
          //  scope 是undefinde 1.直接获取收货地址
          //  scope 是true  用户曾经点过用户权限
          // scope false  用户曾经取消授权

    import regeneratorRuntime from '../../lib/runtime/runtime.js';
    import {getSetting,OpenSetting,chooseAddress,showModal,showToast} from '../../utils/asyncWx.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addreess: {},
    cart: {},
    // 全选状态，总价格，总数量
    isAllChecked: false,
    totalPrice:0,
    totalNum:0,
    hasGoods: false,
  },

  onShow(){
     let cart = wx.getStorageSync("cart") || {};
   this.setData({
     addreess: wx.getStorageSync("addreess") || {},
     cart: cart
    });
    this.setCart(cart);
  },
  // 添加收货地址
 async handleChooseAddress(){
  // 1. 获取用户对该应用的授权信息
    const resul1 = await getSetting();
    const scopeAddress = resul1.authSetting["scope.address"];
    if(scopeAddress === true || scopeAddress === undefined){
      // const result2 = await chooseAddress();

    }else{
      await OpenSetting();
    }
    const result2 = await chooseAddress();
    console.log(result2);
    // 1.3将数据存储在本地
    result2.all = result2.provinceName+result2.cityName+result2.countyName+result2.detailInfo;
    wx.setStorageSync("addreess", result2);
    
  },
// 计算总价
setCart (cart){
  // 把对象转化为数组
  let cartArr = Object.values(cart);

  // 2.计算总的价格
  let totalPrice = 0;
  let totalNum = 0;
  cartArr.forEach((e,i) =>{
    if(e.checked){
      totalPrice += e.goods_price * e.num;
      totalNum += e.num;
    };
  });

  this.setData({cart,totalPrice,totalNum});
  wx.setStorageSync("cart", cart);

},

// 全选

// 结算按钮
async handlePay (){
  // 1.获取data中的地址
  const {addreess,cart} = this.data;
  const cartArr = Object.values(cart);
  let cartChecked = cartArr.some(v => v.checked);
  if(!addreess.all){
    await showToast({title: '您没有选择收货地址'});
  }else if(!cartChecked){
    // 不满足
    await showToast({title: '您没有选择商品'});
  }else{
    wx.navigateTo({
      url: '/pages/pay/index',
    });
      
  }
}

})